package com.metel.mservice.common.utils;

import java.util.Random;

public class OtpValidation {

	public static void main(String[] args) {
		String msisdn="821081568191";
		String authnum = genAuthnum();
		String token = genToken(msisdn, authnum);
		int validate = validationuser(msisdn, token, authnum);
		
		System.out.println(token);
		System.out.println(authnum);
		System.out.println(validate);
		
	}

	public static String genAuthnum(){
		Random rangen = new Random();
		String authnum = "";
		for (int i = 0; i < 6; i++) {
			authnum += Integer.toString((rangen.nextInt(10)));
		}
		
		return authnum;
	}
	public static String genToken(String msisdn, String authnum) {
		byte[] bTimeStamp = new byte[16];
		bTimeStamp = (authnum + authnum + authnum + authnum).getBytes();
		String sTempMsisdn = "";
		if (msisdn.length() >= 16) {
			sTempMsisdn = msisdn.substring(msisdn.length() - 16);
		} else {
			sTempMsisdn = msisdn + msisdn.substring(0, (16 - msisdn.length()));
		}

		byte[] bEncryptKey = new byte[16];
		bEncryptKey = sTempMsisdn.getBytes();
		byte[] bIV = new byte[16];
		for (int i = 0; i < 16; i++) {
			bIV[i] = (byte) (bEncryptKey[i] ^ bTimeStamp[i]);
		}
		StringBuffer sb = new StringBuffer(bIV.length * 2);
		String hexNumber;
		for (int x = 0; x < bIV.length; x++) {
			hexNumber = "0" + Integer.toHexString(0xff & bIV[x]);
			sb.append(hexNumber.substring(hexNumber.length() - 2));
		}
		String token = sb.toString();
		return token;
	}
	public static int validationuser(String msisdn, String token, String authnum) {
		if (msisdn == null || msisdn.trim().length() == 0) {
			return 1;
		}

		if (token == null || token.trim().length() == 0) {
			return 1;
		}
		if (authnum == null || authnum.trim().length() == 0) {
			return 1;
		}

		byte[] bEncryptKey2 = new byte[16];
		byte[] bTimeStamp2 = new byte[16];
		bTimeStamp2 = (authnum + authnum + authnum + authnum).getBytes();
		String sTempMsisdn2 = "";
		if (msisdn.length() >= 16) {
			sTempMsisdn2 = msisdn.substring(msisdn.length() - 16);
		} else {
			sTempMsisdn2 = msisdn + msisdn.substring(0, (16 - msisdn.length()));
		}

		bEncryptKey2 = sTempMsisdn2.getBytes();
		byte[] bIV2 = new byte[16];
		for (int i = 0; i < 16; i++) {
			bIV2[i] = (byte) (bEncryptKey2[i] ^ bTimeStamp2[i]);
		}
		StringBuffer sb2 = new StringBuffer(bIV2.length * 2);
		String hexNumber2;
		for (int x = 0; x < bIV2.length; x++) {
			hexNumber2 = "0" + Integer.toHexString(0xff & bIV2[x]);
			sb2.append(hexNumber2.substring(hexNumber2.length() - 2));
		}

		String verificationkey2 = sb2.toString();

		if (verificationkey2.equals(token)) {
		} else {
			return 2;
		}

		return 0;
	}

}
